import 'package:flutter01/pages/sqfLite/models/target.dart';
import 'package:flutter01/pages/sqfLite/sqflite_providers/base_table_provider.dart';
import 'package:flutter01/pages/sqfLite/utils/date_time.dart';
import 'package:sqflite/sqflite.dart';

enum FilterType {
  all,
  processing,
  completed,
  gaveUp,
}

class TargetTableProvider extends BaseTableProvider {
  TargetTableProvider([tableName = "target"]) : super(tableName);

  //表列名
  final String columnId = "id";
  final String columnTargetName = "t_name";
  final String columnTargetDays = "t_days";
  final String columnTargetColors = "t_colors";
  final String columnTargetSoundKey = "t_sound_key";
  final String columnTargetNotificationTimes = "t_notification_time";
  final String columnTargetCreateTime = "t_create_time";
  final String columnTargetDeleteTime = "t_delete_time";
  final String columnTargetGiveUpTime = "t_giveUp_time";

  @override
  String createTableString() {
    return '''CREATE TABLE $tableName(
    $columnId INTEGER PRIMARY KEY AUTOINCREMENT,
    $columnTargetName TEXT NOT NULL,
    $columnTargetDays INTEGER NOT NULL,
    $columnTargetColors TEXT,
    $columnTargetSoundKey TEXT NOT NULL,
    $columnTargetNotificationTimes TEXT,
    $columnTargetCreateTime TEXT NOT NULL,
    $columnTargetDeleteTime TEXT,
    $columnTargetGiveUpTime TEXT)''';
  }

  // 新增一条目标 insert
  Future insertTarget(Target target) async {
    Database db = await getDataBase();
    String name = target.name!;
    int days = target.targetDays!;
    String? colors = target.targetColor == null
        ? null
        : '${target.targetColor!.red}|${target.targetColor!.green}|${target.targetColor!.blue}';
    String soundKey = target.soundKey!;
    String? notificationTimes;
    if (target.notificationTimes != null) {
      String times = "";
      for (int i = 0; i < target.notificationTimes!.length; i++) {
        times += timeOfDayToString(target.notificationTimes![i])!;
        if (i < target.notificationTimes!.length - 1) {
          times += "|";
        }
      }
      notificationTimes = times;
    }
    DateTime now = DateTime.now();
    String nowString =
        formatTime(formatter: 'yyyy.MM.dd HH:mm:ss', dateTime: now)!;
//执行插入操作
    return await db.transaction((txn) async {
      int rowId = await txn.rawInsert(
          'INSET INTO $tableName($columnTargetName,$columnTargetDays,$columnTargetColors,$columnTargetSoundKey,$columnTargetNotificationTimes,$columnTargetCreateTime) VALUES($name,$days,$colors,$soundKey,$notificationTimes,$nowString)');
      return {'rowId': rowId, 'createIme': now};
    });
  }

// 查询所有目标 select
  Future<List<Target>> queryTargets(
      {FilterType filterType = FilterType.all}) async {
    Database db = await getDataBase();

    String? sql;
    if (filterType == FilterType.gaveUp) {
      //查询已放弃的目标
      sql =
          'SELECT * FROM $tableName WHERE $columnTargetGiveUpTime IS NOT NULL ORDER BY $columnTargetCreateTime DESC';
    } else if (filterType == FilterType.processing ||
        filterType == FilterType.completed) {
      sql =
          'SELECT * FROM $tableName WHERE $columnTargetGiveUpTime IS NULL ORDER BY $columnTargetCreateTime DESC';
    } else {
      //查询全部
      sql = 'SELECT * FROM $tableName ORDER BY $columnTargetCreateTime DESC';
    }
    List<Map<String, dynamic>> results = await db.rawQuery(sql);
    List<Target> targets = [];
    results.forEach((element) {
      Target? target = Target.targetFromMap(element);
      if (target != null) {
        targets.add(target);
      }
    });
    return targets;
  }

// 修改目标 update
  Future updateTarget(Target target) async {
    //只能更新 颜色，通知时间，声音，
    Database db = await getDataBase();
    String? colors = target.targetColor == null
        ? null
        : '${target.targetColor!.red}|${target.targetColor!.green}|${target.targetColor!.blue}';
    String? notificationTimes;
    if (target.notificationTimes != null) {
      String times = "";
      for (int i = 0; i < target.notificationTimes!.length; i++) {
        times += timeOfDayToString(target.notificationTimes![i])!;
        if (i < target.notificationTimes!.length - 1) {
          times += "|";
        }
      }
      notificationTimes = times;
    }
    String soundKey = target.soundKey!;
    return await db.transaction((txn) async {
      String sql =
          'UPDATE $tableName SET $columnTargetColors = ?,$columnTargetSoundKey = ?,$columnTargetNotificationTimes = ? WHERE $columnId = ?';
      int count = await txn
          .rawUpdate(sql, [colors, soundKey, notificationTimes, target.id]);
      return count;
    });
  }

  // 放弃某个目标
  Future giveUpTarget(Target target) async {
    Database db = await getDataBase();
    String now =
        formatTime(formatter: 'yyyy.MM.dd HH:mm:ss', dateTime: DateTime.now())!;
    return await db.transaction((txn) async{
      String sql = 'UPDATE $tableName SET $columnTargetGiveUpTime = ? WHERE $columnId = ?';
      int count = await txn.rawUpdate(sql,[now,target.id]);
      return count;
    });
  }
}
